<template>
  <div class="product-edit-view">
    <el-steps
      :active="active"
      finish-status="success"
      simple
      style="margin-top: 20px"
    >
      <el-step
        class="step"
        :title="step"
        v-for="(step, index) in steps"
        :key="step"
        @click.native="active = index"
        icon="el-icon-edit"
      ></el-step>
    </el-steps>

    <!--  动态组件  -->
    <keep-alive>
      <transition name="fade-transform" mode="out-in">
        <component
          :is="components[active]"
          v-bind.sync="form"
          ref="component"
        ></component>
      </transition>
    </keep-alive>

    <div class="product-edit__footer">
      <div>
        <el-button>上一步</el-button>
        <el-button @click="next">下一步</el-button>
      </div>
      <div>
        <el-button type="danger" v-if="active !== 1">清空</el-button>
        <el-button type="primary" @click="onSubmit" v-if="active !== 2"
          >保存</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import ProductEditBasic from "./components/ProductEditBasic";
import ProductEditDetail from "./components/ProductEditDetail";
import ProductEditImage from "./components/ProductEditImage";

export default {
  name: "ProductEditView",
  // eslint-disable-next-line vue/no-unused-components
  components: { ProductEditImage, ProductEditDetail, ProductEditBasic },
  props: {
    product: {
      type: Object,
      default() {
        return {
          id: "",
          images: [],
          is_published: true,
          name: "",
          description: "",
          stock: 0,
          price: 0,
          subtitle: "",
          sale_price: 0,
          short_desc: "",
          display_image: "",
          category: "",
        };
      },
    },
  },
  data() {
    return {
      active: 0,
      steps: ["编辑基本信息", "编辑详情信息", "编辑图片"],
      components: ["ProductEditBasic", "ProductEditDetail", "ProductEditImage"],
      form: { ...this.product },
    };
  },
  watch: {
    product: {
      deep: true,
      handler() {
        this.form = { ...this.product };
      },
    },
  },
  methods: {
    async onSubmit() {
      try {
        this.$refs.component.validate &&
          (await this.$refs.component.validate());
      } catch (e) {
        console.log(e);
        return;
      }

      if (this.form.id) {
        await this.$api.editProduct(this.form);
        this.$message.success("更新成功！");
      } else {
        const result = await this.$api.addProduct(this.form);
        this.form = result;
      }
    },
    next() {
      if (this.active === 0) {
        if (!this.form.id) {
          this.$message.warning("必须完成第一步才能进行下一步");
          return;
        }
      }
      this.active++;
    },
  },
};
</script>

<style scoped>
.step {
  cursor: pointer;
}
.product-edit__footer {
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
}
</style>
